const app = getApp();
var thatAll;
const BT = JSON.stringify(Str2Bytes("aa55a55a")); //通用包头
const BW = JSON.stringify(Str2Bytes("cc66c66c")); //通用包尾
const  writeServicesId="0000FFE5-0000-1000-8000-00805F9B34FB"
const  writeCharacteristicsId= "0000FFE9-0000-1000-8000-00805F9B34FB" //写UUID， 根据蓝牙模块获得
const notifyServicesId="0000FFE0-0000-1000-8000-00805F9B34FB"//响应
const notifyCharacteristicsId= "0000FFE4-0000-1000-8000-00805F9B34FB" //响应UUID，根据蓝牙模块获得
var connectedDeviceId = "" //连接上的设备的ID
Page({
  data: {
    state:1,
    nowIdentity:"",
    configYear:"23",
    configMonth:"12",
    configP:"01",
    configFirst:"00",
    configLast:"00",
    eqFirst:"40",
    dianliang:"",
    zhuangtai:""
  },
   onShow :function () {
     //体验版：体验版删除数据，发布时屏蔽掉
     if(app.nowEquipmentId){
      this.setData({
        nowIdentity : app.nowEquipmentId
      })
     }
   },
  //高度
  onLoad: function () {
    var that = this;
    thatAll = that;
   //体验版：体验版删除数据，发布时屏蔽掉
   if(app.nowEquipmentId){
    this.setData({
      nowIdentity : app.nowEquipmentId
    })
   }
  },
  fanzhuan:function () {
    BLEDataSend("aa55a55a210100cc66c66c");
   },
   fanzhuanS:function () {
    BLEDataSend("aa55a55a210101cc66c66c");
   },
   fanzhuanX:function () {
    BLEDataSend("aa55a55a210102cc66c66c");
   },
   danci:function () {
    this.setData({
      zhuangtai:"0"
    })
    BLEDataSend("aa55a55a2000cc66c66c");
   },
   wushi:function () {
    this.setData({
      zhuangtai:"01"
    })
    BLEDataSend("aa55a55a2001cc66c66c");
   },
   zidong:function () {
     this.setData({
       zhuangtai:"02"
     })
    BLEDataSend("aa55a55a2002cc66c66c");
   },
   pinlv:function (e) {
    BLEDataSend("aa55a55a210101cc66c66c");
   },
     /**体验版设置：加减 */
  configAddReduce(e){
    var that = this;
    var prop = e.target.dataset.prop;
    var type = e.target.dataset.type;
    if(prop == "configYear"){
      var configYear = that.data.configYear;
      if(type == 'add'){
        configYear = parseInt(configYear) + 1;
      }else if(type == 'reduce'){
        if(configYear > 1){
          configYear = parseInt(configYear) - 1;
        }
      }
      that.setData({
        configYear : formatNumber(configYear)
      })
    }else if(prop == "configMonth"){
      var configMonth = that.data.configMonth;
      if(type == 'add'){
        if(configMonth <12){
          configMonth = parseInt(configMonth)+1;
        }else{
          configMonth = 1;
        }
      }else if(type == 'reduce'){
        if(configMonth >1){
          configMonth = parseInt(configMonth) - 1;
        }else{
          configMonth = 12;
        }
      }
      that.setData({
        configMonth: formatNumber(configMonth)
      })
    }else if(prop == "configP"){
      var configP = that.data.configP;
      if(type == 'add'){
        if(configP < 9){
          configP = parseInt(configP)+1;
        }else{
          configP = 1;
        }
      }else if(type == 'reduce'){
        if(configP > 1){
          configP = parseInt(configP) - 1;
        }else{
          configP = 9;
        }
      }
      that.setData({
        configP: formatNumber(configP)
      })
    }else if(prop == "configFirst"){
      var configFirst = that.data.configFirst;
      if(type == 'add'){
        if(configFirst < 99){
          configFirst =  parseInt(configFirst)+1;
        }else{
          configFirst = 0;
        }
      }else if(type == 'reduce'){
        if(configFirst > 0){
          configFirst =  parseInt(configFirst) - 1;
        }else{
          configFirst = 99;
        }
      }
      that.setData({
        configFirst: formatNumber(configFirst)
      })
    }else if(prop == "configLast"){
      var configLast = that.data.configLast;
      if(type == 'add'){
        if(configLast < 99){
          configLast =  parseInt(configLast)+1;
        }else{
          configLast = 0;
        }
      }else if(type == 'reduce'){
        if(configLast > 0){
          configLast =  parseInt(configLast) - 1;
        }else{
          configLast = 99;
        }
      }
      that.setData({
        configLast: formatNumber(configLast)
      })
    }
  },
  /**体验版设置： 单选框*/
  handleChange(e){
     var that = this;
     that.setData({
       eqFirst:e.detail.value
     })
  },
  /**体验版设置：修改设备号 */
  changeEqName(){
    var that = this;
    var year = that.data.configYear;
    var configMonth = that.data.configMonth;
    var configFirst = that.data.configFirst;
    var configLast = that.data.configLast;
    var message = "aa55a55a260400"+
    formatNumber(parseInt(year[0]).toString(16))+
    formatNumber(parseInt(year[1]).toString(16))+
    formatNumber(parseInt(configMonth[0]).toString(16))+
    formatNumber(parseInt(configMonth[1]).toString(16))+
    formatNumber(parseInt(configFirst[0]).toString(16))+
    formatNumber(parseInt(configFirst[1]).toString(16))+
    formatNumber(parseInt(configLast[0]).toString(16))+
    formatNumber(parseInt(configLast[1]).toString(16))+
    "cc66c66c";

    //console.log("message："+message);
    BLEDataSend(message);
   //sendTy("444D313032333035313033303130");
   //sendTy(newName);

  },
    /**体验版设置：输入框值改变 */
    inputOnChange(e) {
      this.setData({
        [e.currentTarget.dataset.prop]:e.detail.value
      });
    },
   /**
    * 点击事件
   */
   index:function(e){
    var that = this;
    var state = e.currentTarget.dataset.state;
    if(state == 1){
      wx.navigateTo({
        url: '/pages/index/index',
      });
    }else{
      closeBLEConnection();
    }
   },

});

/**    蓝牙        */








  /****************5.连接蓝牙设备***************/
  function BLEConnect(event)
  {
    wx.createBLEConnection
    ({
      deviceId: event.target.id,
      timeout:20000,
      success: function (res) 
      {
        //console.log("red："+JSON.stringify(res))
          wx.getBLEDeviceServices({
            deviceId:event.target.id,
            success:function(res){
              for(var i=0;i<res.services.length;i++){
                // console.log(res.services[i].uuid);
                var serviceId =  res.services[i].uuid;
                wx.getBLEDeviceCharacteristics({
                  deviceId: event.target.id,
                  serviceId:serviceId,
                  success:function(res){
                    for (let i = 0; i < res.characteristics.length; i++) {
                      if(res.characteristics[i].uuid == notifyCharacteristicsId){
                             thatAll.setData({
                              state : 2,
                            });
                            var identity = event.currentTarget.dataset.identity;//连接的设备名字
                            app.identity = identity.replace(/[\r\n ]/g,"");//全局变量
                            app.nowEquipmentId = app.identity;
                            connectedDeviceId= event.currentTarget.id;//连接设备id
                         //连接设备id
                            BLECharacteristicValueChange();//启用特征值变化
                            BLEDataRecieve();//接收信息
                          
                            jiance()//监测状态 
                              wx.switchTab({
                                url: '/pages/home/home',
                              });
                          
                             
                    
                      }
                    }
                  }
          
                })
            }
          }
          })
        //getBLEDeviceServices(event.target.id);
      },
      fail: function (res) 
      {
        console.log("fail："+JSON.stringify(res))
        wx.showModal({
          title: '提示',
          content:  res.errMsg,
          success (res) {
       
          }
        })
      },
      complete:function(){
        BLESearchStop();
      }
    })
  }

 function getBLEDeviceServices(deviceId) {
  return promisify(wx.getBLEDeviceServices, {
    deviceId: deviceId
  }).then(res => {
    for(var i=0;i<res.services.length;i++){
      //       console.log(res.services[i].uuid);
    }
      return res
  }, err => {
   // console.log("失败："+res)
      return err
  })

  }
  function promisify(fn, args) {
    return new Promise((resolve, reject) => {
        fn({
            ...(args || {}),
            success: (res) => resolve(res),
            fail: (err) => reject(err),
        });
    });
}
  /****************6.停止搜索蓝牙设备***************/
  function BLESearchStop(event)
  {
    wx.stopBluetoothDevicesDiscovery
    ({
      success: function (res) 
      {
       // console.log("停止搜索" + JSON.stringify(res.errMsg));
      }
    })
  }
  /****************9.启用特征值变化***************/
  function BLECharacteristicValueChange(event)
  {
   // console.log("启用的notifyCharacteristicsId", notifyCharacteristicsId);
    wx.notifyBLECharacteristicValueChange
    ({
      state: true,
      deviceId: connectedDeviceId,
      serviceId: notifyServicesId,//响应
      characteristicId: notifyCharacteristicsId,
      success: function (res) 
      {
        // console.log('notifyBLECharacteristicValueChange success', res.errMsg)
      },
      fail: function (res) 
      {
        //.log('启动notify:' + res.errMsg);
      },
      
    })
  }
  /****************10.接收蓝牙的返回数据***************/
  function BLEDataRecieve(event)
  {
   // console.log("开始接收数据");
    wx.onBLECharacteristicValueChange
    (
      function (res) 
      {
        //可以直接setdata设置显示数据
       // console.log("characteristicId：" + res.characteristicId)
       // console.log("serviceId:" + res.serviceId)
        //console.log("deviceId" + res.deviceId)
        //console.log("Length:" + res.value.byteLength)
        var data = ab2hex(res.value);
        console.log("返回数据:" + data)
        var bytes = Str2Bytes(data);
        analysis(bytes);//数据解析 
      
      }
    )
  }
  //监测
  function jiance() {
    wx.onBLEConnectionStateChange(function(res) {
   // 该方法回调中可以用于处理连接意外断开等异常情况
    if(res.connected){
      thatAll.setData({
        state : 2
      })
    }else{
      thatAll.setData({
        state : 1,
        nowIdentity:""
      });
      closeBLEConnection();
    }
    // console.log(thatAll.data.state)
    // console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
})
  }
 //数据解析
  function analysis(bytes){
      for(var i=0;i<bytes.length;i++){ 
          //剩余长度大于2
          if(i < bytes.length - 2){
              //1.家长设置
              //验证包头
            if(BT == JSON.stringify(bytes.slice(i,i+4))){
                //验证包尾
              if(BW == JSON.stringify(bytes.slice(i+7,i+11))){//包左不包右,3个包体
                  //判断指令包
                  var type = bytes[i+4];
                  console.log("3包体，类型："+type)
                  if(type == "1f"){
                    //握手回复
                    BLEDataSend("aa55a55a2f5152cc66c66c");
                  }
              }
              if(BW == JSON.stringify(bytes.slice(i+6,i+10))){//包左不包右，2个包体
                //判断指令包
                var type = bytes[i+4];
                var model = bytes[i+5];
                console.log("2包体，类型："+type)
                if(type == "10"){
                  var zt = "";
                  if(model =="00"){
                    zt = "单次"
                  }else if(model =="01"){
                    zt = "雾视"
                  }else if(model =="02"){
                    zt = "自动"
                  }
                  thatAll.setData({
                    zhuangtai : zt
                  })
                }else if(type == "15"){
                  thatAll.setData({
                    dianliang : model
                  })
                }else if(type == "1e"){
                  wx.showToast({
                    title: '命令回复：'+model,
                    icon: "none",
                    mask: false, 
                    duration:1000 
                  })
                }
               
            }
            }
          }
      }
  }

/****************11.蓝牙发送数据***************/
 function BLEDataSend(message){
  console.log('要发送的信息是：'+message)
  var buffer1 = string2ArrayBuffer(message);
  console.log(buffer1)
  wx.writeBLECharacteristicValue
  ({
    deviceId: connectedDeviceId,
    serviceId: writeServicesId,
    characteristicId: writeCharacteristicsId,
    // 这里的value是ArrayBuffer类型
    value: buffer1,
    success: function (res) 
    {
     // console.log('写入成功', res.errMsg)
    },
    fail(res)
    {
    //  console.log('写入失败', res.errMsg)
    }
  })
}
  //开始治疗
 function uploadData(type,pricePY,treatTimePT,priceHz,priceZY,treatTimeZY,bx,fs){//这里可以传个参数判断是哪个设置
    if(type ==1){
    //  console.log("强度："+pricePY +"  时长："+treatTimePT)
    //都转成16进制的，并自动补0
    var qd = formatNumber(parseInt(pricePY).toString(16));//强度
    var time = formatNumber(parseInt(treatTimePT).toString(16));//时长
    var plh = formatNumber("00");//频率高字节
    var pld = formatNumber("04");//频率低字节
    var zb = formatNumber("06");//载波
    BLEDataSend(XFJZ.concat(qd,time,plh,pld,zb,BW));
    }else if (type ==2){
     var hzH = formatNumber(parseInt(priceHz/100).toString(16));//频率高字节
     var hzD = formatNumber((parseInt(priceHz) % 100).toString(16));//频率低字节
     var dl = formatNumber(parseInt(priceZY).toString(16));//电流
     var bx = formatNumber(parseInt(bx).toString(16));//波形
     var fs = formatNumber(parseInt(fs).toString(16));//方式
     var dj = formatNumber("03");//电极
     var time = formatNumber(parseInt(treatTimeZY).toString(16));//时长
     var zb = formatNumber("06");//载波
    // console.log("频率："+priceHz +"  时长："+treatTimeZY+" 强度："+priceZY)
     BLEDataSend(XFZY.concat(hzH,hzD,dl,bx,fs,dj,time,zb,BW));
    }
  }
  //断开蓝牙
  function closeBLEConnection(){
    wx.closeBLEConnection({
      deviceId: connectedDeviceId,
      success: function (res) {
        connectedDeviceId= "",
        wx.showToast({
          title: '蓝牙已断开',
          icon: "none",
          mask: false, 
          duration:1000 
        })
        thatAll.setData({
          state :1,
          nowIdentity:""
        });
      },
      fail:function(res){
       // console.log('断开蓝牙设备失败：' + res.errMsg)
      }
    })

  }

/**字符串转16进制 */
function stringToHex(str){
  var val = "";
  for (var i = 0; i < str.length; i++) {
      if (val == "") {
          val = str.charCodeAt(i).toString(16);        //获取字符的Unicode码然后转16进制
      } else {
          val += str.charCodeAt(i).toString(16);//获取字符的Unicode码然后转16进制再拼接,中间用逗号隔开
      }
  }
  return val;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  const hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
 // console.log("类型："+Object.prototype.toString(hexArr))
  return hexArr.join('');
}
function string2ArrayBuffer(val) { //传过来是字符串类型指令  包头+包体+包尾
  // 首先将字符串转为16进制
  //let val = ""
  // for (let i = 0; i < str.length; i++) {
  //   if (val === '') {
  //     val = str.charCodeAt(i).toString(16) 
  //   } else {
  //     val += ',' + str.charCodeAt(i).toString(16)
  //   }
  // }
  // 将16进制转化为ArrayBuffer
  return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h, 16)
  })).buffer
}
function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}
function Str2Bytes(str)
{
    var pos = 0;
    var len = str.length;
    if(len %2 != 0)
    {
       return null;
    }
    len /= 2;
    var hexA = new Array();
    for(var i=0; i<len; i++)
    {
        var s = str.substr(pos, 2);
       // var v = parseInt(s, 16);
        hexA.push(s);
        pos += 2;
    }
    return hexA;
}

//补0
const formatNumber = (num) => {
	num = num.toString()
	return num[1] ? num : '0' + num
}
//截取字符串
function substrBytes(bytes,begin,end){
  return  bytes.slice(begin,end);
}



module.exports = {
  uploadData: uploadData,
  BLEConnect:BLEConnect,
  BLEDataSend:BLEDataSend,
  closeBLEConnection:closeBLEConnection,
}